//
//  MainViewController.m
//  Mayhem
//
//  Created by Jay Meistrich on 6/20/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MainViewController.h"

@implementation MainViewController

BOOL isError = false;

@synthesize webView;
@synthesize activityIndicator;
@synthesize labelStatus;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    isShowing = true;
    ipAttempt = 0;
    
    [webView setOpaque:NO];
    [webView setBackgroundColor:[UIColor clearColor]];
    
    for (id subview in webView.subviews)
        if ([[subview class] isSubclassOfClass: [UIScrollView class]])
            ((UIScrollView *)subview).bounces = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ServiceIPSet:) name:@"ServiceIPSet" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NeedsSettings:) name:@"NeedsSettings" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Connect:) name:@"Connect" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Disconnect:) name:@"Disconnect" object:nil];
    
    [self ConnectToService];
}

- (void)Disconnect: (NSNotification *)notification
{
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
}

- (void)Connect: (NSNotification *)notification
{
    [self ConnectToService];
}

- (void)NeedsSettings: (NSNotification *)notification
{
    [self showInfo:nil];
}

- (void)ServiceIPSet: (NSNotification *)notification
{
    [self ConnectToService];
}

- (void)ConnectToService
{
    isError = false;
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *ip = [prefs stringForKey:@"IP"];
    if(ip != nil && [ip length] > 0)
    {
        NSString *port = [prefs stringForKey:@"Port"];
        if([port length] > 0)
        {
            if([ip rangeOfString:@";"].location != NSNotFound)
            {
                NSArray *ips = [ip componentsSeparatedByString:@";"];
                if(++ipAttempt > [ips count] - 1)
                    ipAttempt = 0;
                
                ip = [ips objectAtIndex:ipAttempt];
            }
            [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
            
            NSString *address = [NSString stringWithFormat:@"http://%@:%@/Mayhem/Html",ip,port];
        
            NSURL *url = [NSURL URLWithString:address];
            NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
            [webView loadRequest:request];
        }
        else
            [labelStatus setText:@""];
    }
    else
        [labelStatus setText:@""];
}

- (void)setError
{
    /*
    [activityIndicator stopAnimating];
    [labelStatus setText:@"Connection error"];
    [labelStatus setTextColor:[UIColor redColor]];
    labelStatus.alpha = 1;
    */
    if(isShowing)
    {
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ConnectToService) userInfo:nil repeats:NO];
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self setError];
    ///TODO: Check error code and do something different if no network
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    if(!isError)
    {
        [activityIndicator startAnimating];
        [labelStatus setText:@"Connecting..."];
        [labelStatus setTextColor:[UIColor grayColor]];
        labelStatus.alpha = 1;
    }
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSURL *url = self.webView.request.URL;
    if(![[url absoluteString] isEqualToString:@"about:blank"])
    {
        [activityIndicator stopAnimating];
        [labelStatus setText:@""];
        labelStatus.alpha = 0;
        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        NSString *ip = [prefs stringForKey:@"IP"];

        if([ip rangeOfString:@";"].location != NSNotFound)
        {
            NSArray *ips = [ip componentsSeparatedByString:@";"];
            
            ip = [ips objectAtIndex:ipAttempt];
            [prefs setObject:ip forKey:@"IP"];
            [prefs synchronize];
        }

    }
}
- (BOOL)webView:(UIWebView *)webView 
                shouldStartLoadWithRequest:(NSURLRequest *)request 
                navigationType:(UIWebViewNavigationType)navigationType 
{
	NSString *requestString = [[request URL] absoluteString];
	NSArray *components = [requestString componentsSeparatedByString:@":"];
    
	if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"mayhem"]) 
    {
		if([(NSString *)[components objectAtIndex:1] isEqualToString:@"error"]) 
		{
            isError = true;
            [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
            [self setError];
		}
		return NO;
	}
    
	return YES; // Return YES to make sure regular navigation works as expected.
}

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
    [self dismissModalViewControllerAnimated:YES];
    
    isShowing = true;
    [self ConnectToService];
}

- (IBAction)showInfo:(id)sender
{    
    isShowing = false;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
    FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
    controller.delegate = self;
    
    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:YES];
    
    [controller release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload
{
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc
{
    [super dealloc];
}

@end
